package com.liu.nb.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.nb.entity.SysRole;
import com.liu.nb.entity.SysRoleMenu;
import com.liu.nb.entity.SysUserRole;
import com.liu.nb.util.Const;
import com.liu.nb.util.Result;
import io.netty.handler.timeout.IdleState;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author liuziyi
 * @since 2021-08-05
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController{

    @PreAuthorize("hasAuthority('sys:role:list')")
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable Long id){
        SysRole sysRole = sysRoleService.getById(id);
//      获取角色相关联的菜单id
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> collect = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());

        sysRole.setMenuIds(collect);
        return Result.success(sysRole);
    }
    @PreAuthorize("hasAuthority('sys:role:list')")
    @RequestMapping("/list")
    public Result list(String name){
        Page<SysRole> sysRolePage  = sysRoleService.page(getPage(), new QueryWrapper<SysRole>().like(StrUtil.isNotBlank(name), "name", name));
        return Result.success(sysRolePage);
    }
    @PreAuthorize("hasAuthority('sys:role:save')")
    @RequestMapping("/save")
    public Result save(@Validated @RequestBody SysRole sysRole){
//        sysRole.setCreated(LocalDateTime.now());
        boolean save = sysRoleService.save(sysRole);
        return Result.success(save);
    }
    @PreAuthorize("hasAuthority('sys:role:update')")
    @RequestMapping("/update")
    public Result update(@Validated @RequestBody SysRole sysRole){
        sysRole.setUpdated(LocalDateTime.now());
        boolean b = sysRoleService.updateById(sysRole);
        //删除旧缓存
        sysUserService.clearAuthorityInfoByRoleId(sysRole.getId());
        return Result.success(b);
    }
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @RequestMapping("/delete")
    @Transactional
    public Result info(@RequestBody Long[] roleIds){
        boolean b = sysRoleService.removeByIds(Arrays.asList(roleIds));
        //删除和该角色相关的信息
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", roleIds));
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id",roleIds));
        //删除旧缓存
        for (Long roleId : roleIds) {
            sysUserService.clearAuthorityInfoByRoleId(roleId);
        }
        return Result.success(b);
    }
    @PreAuthorize("hasAuthority('sys:role:perm')")
    @Transactional
    @PostMapping("/perm/{roleid}")
    public Result info(@PathVariable("roleid") Long roleId, @RequestBody Long[] menuIds){
       List<SysRoleMenu> sysRoleMenus=new ArrayList<>();
       Arrays.stream(menuIds).forEach(menuId ->{
           SysRoleMenu sysRoleMenu=new SysRoleMenu();
           sysRoleMenu.setMenuId(menuId);
           sysRoleMenu.setRoleId(roleId);
           sysRoleMenus.add(sysRoleMenu);
       });
//       先删除原来的记录，再保存新的
       sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",roleId));
        boolean b = sysRoleMenuService.saveBatch(sysRoleMenus);
        sysUserService.clearAuthorityInfoByRoleId(roleId);
        return Result.success(b);
    }
}
